import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken,getInfo,removeInfo, removeToken} from '@/utils/auth'
import loginApi from "@/api/lejv/login";
import qs from "qs"
import router from "@/router"
var setting = require("@/settings")
let item = getInfo()
// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: setting.host, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout,
  headers:{
    "Content-Type":"application/json;charset=utf-8"
  }
})

// request interceptor 请求拦截器 设置token
service.interceptors.request.use(
  config => {
    if(getToken){
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor 响应拦截器
service.interceptors.response.use(
  response => {
    // console.log(response);
    const res = response.data
    
    if(res.status == 401){
      // Message({
      //   message: "登录超时,请重新登录!",
      //   type: 'error',
      //   duration: 5 * 1000
      // })
      setTimeout(()=>{
        router.push("/login")
        removeInfo()
        removeToken()
      },2000)
    }
    else{
      return res
    }
  },
  error => {
    // console.log( error.response) // for debug
    if(error.response.status == 401){
      Message({
        message: "登陆超时,请重新登录!",
        type: 'error',
        duration: 2 * 1000
      })
      // loginApi.loginout(item.username)
      removeInfo()
      removeToken()
      setTimeout(()=>{
        router.push("/login")
      },2000)
    }else if(error.response.status == 500){
      Message({
        message: "服务器内部错误!",
        type: 'error',
        duration: 2 * 1000
      })
    }else if(error.response.status == 403){
      let num = 5
      let a = Message({
        message: "5s  你当前的权限已变更,请重新登录",
        type: 'error',
        duration: 5 * 1000
      })
      let timer = setInterval(()=>{
        num--
        a.message = ""+num+"s  你当前的权限已变更,请重新登录";
        if(num == 0){
          clearInterval(timer)
        }
      },1000)
      removeInfo()
      removeToken()
      setTimeout(()=>{
        router.push("/login")
      },5000)
    }
    return Promise.reject(error)
  }
)

function http(config){
  if(config.method.toLowerCase() == "post"){ //根据后台格式要求,无需转格式
    // config.data = qs.stringify(config.data,{ arrayFormat: 'repeat' ,allowDots: true})
  }else if(config.method.toLowerCase() == "get"){  //get请求只存在参数在地址栏拼接 put请求参数可在地址栏||请求体中,需在api中写上
    config.params = config.data
    config.data = { unused: 0 } //处理参数为空时 content-type 为空,请求报错
  }
  else{
    // console.log(config)
  }
  return service(config)
}

export default http
